package com.ruoyi.ghxx.controller;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.ghxx.aop.SysInitData;
import com.ruoyi.ghxx.aop.SysInitUpdateData;
import com.ruoyi.ghxx.aop.SysQueryData;
import com.ruoyi.ghxx.domain.*;
import com.ruoyi.ghxx.mqtt.MyMqttClient;
import com.ruoyi.ghxx.service.*;
import com.ruoyi.ghxx.service.impl.RedisServiceImpl;
import com.ruoyi.ghxx.util.Detect;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.servlet.http.HttpServletResponse;

/**
 * 设备实时数据Controller
 *
 * @author ruoyi
 * @date 2022-05-27
 */
@RestController
@RequestMapping("/ghxx/bDeviceRealData")
public class BDeviceRealDataController extends BaseController
{
    @Autowired
    private IBDeviceRealDataService bDeviceRealDataService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private RedisCache redisCache;
/**
 * 查询设备实时数据列表
 */
    @GetMapping("/list")
    //@SysQueryData
    public TableDataInfo list(BDeviceRealData bDeviceRealData)
    {
        startPage();
        List<BDeviceRealData> list=new ArrayList<>();
        if(Detect.isEmpty(bDeviceRealData.getZtGuid())){
            return getDataTable(list);
        }
        list = bDeviceRealDataService.selectBDeviceRealDataList(bDeviceRealData);
        return getDataTable(list);
    }
    
    /**
     * 导出设备实时数据列表
     */
    @Log(title = "设备实时数据", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @SysQueryData
    public void export(HttpServletResponse response, BDeviceRealData bDeviceRealData)
    {
        List<BDeviceRealData> list = bDeviceRealDataService.selectBDeviceRealDataList(bDeviceRealData);
        ExcelUtil<BDeviceRealData> util = new ExcelUtil<BDeviceRealData>(BDeviceRealData.class);
        util.exportExcel(response,list, "变量管理");
    }
    /**
     * 获取设备实时数据详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(bDeviceRealDataService.selectBDeviceRealDataById(id));
    }

    /**
     * 新增设备实时数据
     */
    @Log(title = "设备实时数据", businessType = BusinessType.INSERT)
    @PostMapping
    @SysInitData
    public AjaxResult add(@RequestBody BDeviceRealData bDeviceRealData)
    {
        Integer count = jdbcTemplate.queryForObject("select count(1) from b_device_real_data where zt_guid=? and  param_name=?",
                Integer.class, bDeviceRealData.getZtGuid(),bDeviceRealData.getParamName());
        if (count > 0) {
            return AjaxResult.error("该名称已存在，请勿重复添加");
        }
        Integer countFiled = jdbcTemplate.queryForObject("select count(1) from b_device_real_data where zt_guid=? and  param_field=?",
                Integer.class, bDeviceRealData.getZtGuid(),bDeviceRealData.getParamField());
        if (countFiled > 0) {
            return AjaxResult.error("该标识已存在，请勿重复添加");
        }
        Integer code = bDeviceRealDataService.insertBDeviceRealData(bDeviceRealData);
        redisCache.setCacheObject("RealData-"+bDeviceRealData.getZtGuid()+"-"+bDeviceRealData.getParamField(),bDeviceRealData);
        if(code==200){
            return AjaxResult.success("操作成功");
        }else{
            return AjaxResult.error("操作失败");
        }
    }

    /**
     * 修改设备实时数据
     */
    @Log(title = "设备实时数据", businessType = BusinessType.UPDATE)
    @PutMapping
    @SysInitUpdateData
    public AjaxResult edit(@RequestBody BDeviceRealData bDeviceRealData)
    {
        Integer count = jdbcTemplate.queryForObject("select count(1) from b_device_real_data where  id !=? and param_name=? and zt_guid=?",
                Integer.class, bDeviceRealData.getId(),bDeviceRealData.getParamName(),bDeviceRealData.getZtGuid());
        if (count > 0) {
            return AjaxResult.error("该名称已存在，请勿重复修改");
        }
        Integer countFiled = jdbcTemplate.queryForObject("select count(1) from b_device_real_data where id !=? and zt_guid=? and  param_field=?",
                Integer.class, bDeviceRealData.getId(),bDeviceRealData.getZtGuid(),bDeviceRealData.getParamField());
        if (countFiled > 0) {
            return AjaxResult.error("该标识已存在，请勿重复添加");
        }
        Integer code = bDeviceRealDataService.updateBDeviceRealData(bDeviceRealData);
        redisCache.setCacheObject("RealData-"+bDeviceRealData.getZtGuid()+"-"+bDeviceRealData.getParamField(),bDeviceRealData);
        if(code==200){
            return AjaxResult.success("操作成功");
        }else{
            return AjaxResult.error("操作失败");
        }
    }

    /**
     * 删除设备实时数据
     */
    @Log(title = "设备实时数据", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        int code = bDeviceRealDataService.deleteBDeviceRealDataByIds(ids);
        return AjaxResult.success("远程删除成功");
    }

    /**
     * 指令下发
     */
    @Log(title = "指令下发", businessType = BusinessType.INSERT)
    @PostMapping(value = "/orderSend")
    public AjaxResult orderSend(@RequestBody BDeviceRealData bDeviceRealData) throws Exception
    {
        String topic="IOT/WEBTOPO/DATA/"+bDeviceRealData.getZtGuid();
        JSONObject jsonObject=new JSONObject();
        jsonObject.put(bDeviceRealData.getParamField(),bDeviceRealData.getParamValue());
        MyMqttClient.getInstance().sendMessage(topic,JSON.toJSONString(jsonObject).getBytes("UTF-8"),1,false);
        return AjaxResult.success("指令下发成功");
    }
}
